//
//  SGSContactsViewController.m
//  AgileNYC
//
//  Created by German on 02.08.14.
//  Copyright (c) 2014 Softlegion. All rights reserved.
//

#import "SGSContactsViewController.h"
#import "SGSModelsManager.h"
#import "SGSUtils.h"
#import "SGSAppDelegate.h"
#import "GSTableSection.h"
#import "SGSAppConsts.h"
#import "GSContactViewCell.h"
#import "GSUser.h"
#import "SGSProfileROViewController.h"
//#import "SGSDialogsManager.h"
#import "SGSDelegatesManager.h"

@interface SGSContactsViewController () <UITextFieldDelegate, UISearchBarDelegate>

@property (strong, nonatomic) NSArray * sectionsArray;
@property (strong, nonatomic) NSString * currentSearchString;

@end

@implementation SGSContactsViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.barSearch.delegate = self;
    
    [self loadSessionID];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onStartRenewContacts)
                                                 name:contactsWillRenewNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onEndRenewContacts)
                                                 name:contactsDidRenewNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onErrorRenewContacts)
                                                 name:contactsDidNotRenewNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onEndUpdateContacts)
                                                 name:contactsDidUpdateNotification
                                               object:nil];
    
    [self updateContactsTable];
    
    GSLog(GSLogEvent,@"----- SGSContactsViewController Did Load");
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    GSLog(GSLogEvent,@"----- SGSContactsViewController Did Appear");
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    //[[NSNotificationCenter defaultCenter] removeObserver:self];
    
    [self stopSpinner];
    
    GSLog(GSLogEvent,@"----- SGSContactsViewController Did Disappear");
}

#pragma mark - Notifications

-(void) onStartRenewContacts {
    [self startSpinner];
    GSLog(GSLogInfo, @"[SGSContactsTableViewController] Notification \"%@\" received", contactsWillRenewNotification);
}

-(void) onEndRenewContacts {
    [self updateContactsTable];
    [self stopSpinner];
}

-(void) onEndUpdateContacts {
    [self stopSpinner];
    [self updateContactsTable];
}

-(void) onErrorRenewContacts {
    [self stopSpinner];
}

-(void) onSearchBarTextChange:(NSNotification*) notification {
    
}

#pragma mark - Actions

- (IBAction)onBackButtonClick:(UIButton *)sender {
  [self.navigationController popViewControllerAnimated:YES];
}


- (IBAction)onConnectButtonClick:(UIButton *)sender {
    [[SGSDelegatesManager sharedDelegatesManager].currentEventsVC showConnectionDialog];
}

#pragma mark - Internal functions

-(void) updateContactsTable {
    SGSModelsManager * modelsManager =  [SGSModelsManager sharedModelsManager];

    CGFloat positionY = self.barSearch.frame.origin.y + self.barSearch.frame.size.height + 2;
    CGFloat height = self.view.frame.size.height - positionY;

    if ([modelsManager.arrayOfContacts count]==0) {
        self.tblContactsList.hidden = YES;
        self.pnlNoConnectionsView.hidden = NO;
        
        self.pnlNoConnectionsView.frame = CGRectMake(self.pnlNoConnectionsView.frame.origin.x,
                                                     positionY,
                                                     self.pnlNoConnectionsView.frame.size.width,
                                                     height);
        
    } else {
        self.tblContactsList.hidden = NO;
        self.pnlNoConnectionsView.hidden = YES;

        self.tblContactsList.frame = CGRectMake(self.tblContactsList.frame.origin.x,
                                                positionY,
                                                self.tblContactsList.frame.size.width,
                                                height);

        self.sectionsArray = [self generateSections:modelsManager.arrayOfContacts];
        [self.tblContactsList reloadData];
    }
}

-(void) loadSessionID {
    NSString * sessionID = [[SGSModelsManager sharedModelsManager] currentUser].sessionID;
    
    if ((sessionID) && (![sessionID isEqualToString:@"0"]) && (![sessionID isEqualToString:@"(null)"])) {
        self.labSessionId.text = sessionID;
        self.labSessionId.hidden = NO;
    } else {
        self.labSessionId.hidden = YES;
    }
}


-(NSArray*) generateSections:(NSArray*) arrayOfContacts  {
    NSMutableArray * sectionsArray = [NSMutableArray array];
    
    NSString * currentLetter = nil;
    GSTableSection * section = nil;
    
#if !USE_GROUPED_CONTACTS
    section = [[GSTableSection alloc] init];
    section.sectionName = @"";
    section.items = [NSMutableArray array];
    [sectionsArray addObject:section];
#endif
    
    for (GSUser * user in arrayOfContacts) {
        if ((self.currentSearchString) && ([self.currentSearchString length]>0) && ([[user allUserData] rangeOfString:self.currentSearchString
                                                                                                              options:NSCaseInsensitiveSearch].location==NSNotFound)) {
            continue;
        }
        if ([user.isdeleted boolValue]) {
            continue;
        }
        if ([user.isTemp boolValue]) {
            continue;
        }
        if (!user) {
            continue;
        }
        if ([[user fullName] length]==0) {
            continue;
        }
#if USE_GROUPED_CONTACTS
        NSString * firstLetter;
        
        if ([[user fullName] length]>0) {
            firstLetter = [[user fullName] substringToIndex:1];
        } else {
            firstLetter = @"-";
        }
        
        if (![currentLetter isEqualToString:firstLetter]) {
            section = [[GSTableSection alloc] init];
            section.sectionName = firstLetter;
            section.items = [NSMutableArray array];
            currentLetter = firstLetter;
            [sectionsArray addObject:section];
        } else {
            section = [sectionsArray lastObject];
        }
#endif
        [section.items addObject:user];
    }
    
    return sectionsArray;
}

#pragma mark - Table view data source (UITableViewDelegate, UITableViewDataSource)

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    NSInteger sectionsCount = [self.sectionsArray count];
    
    GSLog(GSLogInfo, @"[GSContactsTableViewController] numberOfSectionsInTableView: %d",sectionsCount);
    
    return sectionsCount;
}

#if USE_GROUPED_CONTACTS
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSString * sectionTitle = [[self.sectionsArray objectAtIndex:section] sectionName];
    
    return sectionTitle;
}
#endif

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    GSTableSection * sec = [self.sectionsArray objectAtIndex:section];
    
    NSInteger rowsCount = [sec.items count];
    
    return rowsCount;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return Delete_Button_Title;
}

- (void)tableView:(UITableView*)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    self.btnBack.hidden = YES;
    self.imgBack.hidden = YES;
}

- (void)tableView:(UITableView*)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    self.btnBack.hidden = NO;
    self.imgBack.hidden = NO;
}


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        GSContactViewCell * cell = (GSContactViewCell*)[tableView cellForRowAtIndexPath:indexPath];
        
        SGSModelsManager * modelsManager = [SGSModelsManager sharedModelsManager];
        
        GSUser * contact = [modelsManager contactBySessionID:[NSNumber numberWithInteger:cell.tag]];
        
        GSLog(GSLogWarning, @"Deleting contact: %@", [contact fullName]);
        
        
        [modelsManager deleteContact:contact onComplete:^(BOOL result, NSError *error) {
            if (result) {
                self.sectionsArray = [self generateSections:modelsManager.arrayOfContacts];
                
                [tableView beginUpdates];
                [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
                if ([tableView numberOfRowsInSection:indexPath.section]==1) {
                    [tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationRight];
                }
                [tableView endUpdates];
            }
        }];
        
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * cellIdentifier = @"ContactCell";
    
    GSContactViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (!cell) {
        cell = [[GSContactViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    
    [cell.spinnerPhoto startAnimating];
    
    GSTableSection * section = [self.sectionsArray objectAtIndex:indexPath.section];
    GSUser * curContact = [section.items objectAtIndex:indexPath.row];
    
    cell.labContactFullName.textAlignment = NSTextAlignmentLeft;
    cell.labContactFullName.lineBreakMode = NSLineBreakByWordWrapping;
    cell.labContactFullName.numberOfLines = 0;
    
    cell.labContactFullName.text = [curContact fullName];
    
    cell.labContactPosition.text = [curContact companyAndPosition];
    cell.labLocation.text = [curContact location];
    
    //cell.imgContactPhoto.hidden = YES;
    cell.imgContactPhoto.image = [UIImage imageNamed:No_Profile_Photo_Name];
    
    //[[SGSModelsManager sharedModelsManager] requestImageForContactByContact:curContact loadToImageView:cell.imgContactPhoto];
    [[SGSModelsManager sharedModelsManager] requestImageForContactByContact:curContact onComplete:^(BOOL result, UIImage *image) {
        cell.imgContactPhoto.image = image;
        [cell.spinnerPhoto stopAnimating];
    }];
    
    cell.tag = [curContact.sessionID integerValue];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    GSContactViewCell * cell = (GSContactViewCell*)[tableView cellForRowAtIndexPath:indexPath];
    
    [[SGSModelsManager sharedModelsManager] makeContactCurrentByID:[NSNumber numberWithInteger:cell.tag]];
    
    GSLog(GSLogInfo, @"Current contact: %@", [[SGSModelsManager sharedModelsManager].currentContact fullName]);
    
    SGSProfileROViewController * vc = [self.storyboard instantiateViewControllerWithIdentifier:@"SGSProfileROViewController"];
    vc.isRequestProfile = NO;
    
    [self.navigationController pushViewController:vc animated:YES];
}

#if USE_GROUPED_CONTACTS
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    NSMutableArray * array = [NSMutableArray array];
    
    if ([self.sectionsArray count]>20) {
        for (GSTableSection * section in self.sectionsArray) {
            [array addObject:section.sectionName];
        }
    }
    
    return array;
}
#endif

#pragma mark - UISearchBarDelegate

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar {
    [searchBar resignFirstResponder];
    [searchBar setShowsCancelButton:NO animated:YES];

    [self.barSearch setText:@""];
    [self searchBar:self.barSearch textDidChange:@""];
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    [searchBar setShowsCancelButton:YES animated:YES];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    SGSModelsManager * modelsManager =  [SGSModelsManager sharedModelsManager];
    self.currentSearchString = searchText;
    
    self.sectionsArray = [self generateSections:modelsManager.arrayOfContacts];
    [self.tblContactsList reloadData];
}

#pragma mark - Spinner

-(void) startSpinner {
    SGSAppDelegate * appDelegate = [UIApplication sharedApplication].delegate;
    [appDelegate startSpinner];
    
}

-(void) stopSpinner {
    SGSAppDelegate * appDelegate = [UIApplication sharedApplication].delegate;
    [appDelegate stopSpinner];
}

#pragma mark - System Functions

- (void)didReceiveMemoryWarning {[super didReceiveMemoryWarning];}


@end
